//
//  SourceDetailContainerView.swift
//  test
//
//  Created by colin on 2019/3/29.
//  Copyright © 2019 colin. All rights reserved.
//

import UIKit
import Then

class SourceDetailContainerView: UIView {
    
    private var headerView:SourceDetailHeaderView?
    private var controllers = [ScrollViewController]()
    
    private lazy var contentScrollView = UIScrollView(frame: CGRect.zero)
    
    private var headerViewOldY:CGFloat = 0
    private var headerViewY:CGFloat = 0

    convenience init(parentController:UIViewController,
                     headerView:SourceDetailHeaderView,
                     controllers:[ScrollViewController]) {
        self.init()
        self.headerView = headerView
        self.controllers = controllers
        
        self.contentScrollView.do {
            $0.isPagingEnabled = true
            $0.showsHorizontalScrollIndicator = false
            $0.showsVerticalScrollIndicator = false
            $0.bounces = false
            $0.delegate = self
            
            let contentView = UIView(frame: CGRect.zero).then {
                for index in 0 ..< controllers.count {
                    let controller = controllers[index]
                    $0.addSubview(controller.view)
                    parentController.addChild(controller)
                    controller.didMove(toParent: parentController)
                    controller.view.snp.makeConstraints({ (make) in
                        make.left.equalToSuperview().offset(UIScreen.main.bounds.width * CGFloat(index))
                        make.top.bottom.equalToSuperview()
                        make.width.equalTo(UIScreen.main.bounds.width)
                        if index == controllers.count - 1 {
                            make.right.equalToSuperview()
                        }
                    })
                }
            }
            $0.addSubview(contentView)
            contentView.snp.makeConstraints({ (make) in
                make.edges.equalToSuperview()
                make.height.equalToSuperview()
            })
            
        }
        
        self.addSubview(self.contentScrollView)
        self.contentScrollView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        self.addSubview(headerView)
        headerView.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.top.equalToSuperview()
            make.height.equalTo(headerView.viewHeight)
        }
        
        let tap = UITapGestureRecognizer(target: self, action: #selector(self.actionTap(_:)))
        tap.cancelsTouchesInView = false
        self.addGestureRecognizer(tap)

        // 修正位置
        for controllerIndex in 0 ..< controllers.count {
            
            let controller = controllers[controllerIndex]
            controller.index = controllerIndex
            
            controller.endDecelerating = { [weak self] (controllerIndex_, scrollView) in
                // 记录header位置
                guard let contentScrollView_ = self?.contentScrollView,
                    let controllers_ = self?.controllers,
                    let headerViewOldY_ = self?.headerViewOldY,
                    let y = self?.headerViewY else {return}
                // 判断当前滑动是哪一页
                let page = Int(floor(contentScrollView_.contentOffset.x / UIScreen.main.bounds.width))
                
                // 不是当前页，不作处理
                if controllerIndex_ != page { return }
                
                // 改变其他scrollview 位置
                if headerViewOldY_ != y {
                    
                    for pageIndex in 0 ..< controllers_.count {
                        if pageIndex != page {
                            // 修正位置
                            if let sc = controllers_[pageIndex].scrollView() {
                                let placeholder = y - headerViewOldY_
                                let y = sc.contentOffset.y
                                sc.contentOffset = CGPoint(x: 0, y: y - placeholder)
                            }
                        }
                    }
                }
                
                self?.headerViewOldY = y
            }
            
            // 滑动代理
            controller.scrollHandle = { [weak self] (controllerIndex_, scrollView) in
                guard let contentScrollView_ = self?.contentScrollView,
                let headerView_ = self?.headerView else {return}
                
                // 判断当前滑动是哪一页
                let page = Int(floor(contentScrollView_.contentOffset.x / UIScreen.main.bounds.width))
                
                // 不是当前页，不作处理
                if controllerIndex_ != page { return }
                
                // 改变头部位置
                let headerHeight = headerView_.viewHeight
                let contentHeight = headerView_.contentHeight
                
                let placeHolderHeight = contentHeight
                
                let offsetY = scrollView.contentOffset.y + headerHeight
                
                if offsetY >= 0 && offsetY <= placeHolderHeight {
                    self?.headerViewY = -offsetY
                } else if offsetY > placeHolderHeight {
                    self?.headerViewY = -placeHolderHeight
                } else if offsetY < 0 {
                    self?.headerViewY =  -offsetY
                }
                                
                self?.headerView?.snp.updateConstraints({ (make) in
                    if let y = self?.headerViewY {
                        make.top.equalToSuperview().offset(y)
                    }
                })
                
            }
        }
    }

    @objc private func actionTap(_ sender:UIGestureRecognizer) {
        guard let headerView_ = self.headerView,let segments = headerView_.segments else { return }
        let point = sender.location(in: headerView_)
        for index in 0 ..< segments.items.count {
            let item = segments.items[index]
            let rect = segments.convert(item.frame, to: headerView_)
            if rect.contains(point) {
                self.headerView?.segments?.selectedIndex = index
                self.contentScrollView.contentOffset = CGPoint(x: UIScreen.main.bounds.width * CGFloat(index), y: 0)
                break
            }
        }
    }
    
}

//MARK - 重载系统的hitTest方法
extension SourceDetailContainerView {
    override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
        
        guard let headerView_ = self.headerView else {
            return super.hitTest(point, with: event)
        }
        
        if headerView_.frame.contains(point) {
            self.contentScrollView.isScrollEnabled = false
            let page = Int(floor(self.contentScrollView.contentOffset.x / UIScreen.main.bounds.width))
            let controller = self.controllers[page]
            if let scrollView = controller.scrollView() {
                return scrollView
            } else {
                return super.hitTest(point, with: event)
            }
        } else {
            self.contentScrollView.isScrollEnabled = true
            return super.hitTest(point, with: event)
        }

    }
}

extension SourceDetailContainerView:UIScrollViewDelegate {
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
//        var placeholderOffset:CGFloat = 0
//
//        let page = Int(floor(self.contentScrollView.contentOffset.x / UIScreen.main.bounds.width))
//        let controller = self.controllers[page]
//
//        if let current = controller.scrollView(),let headerHeight = self.headerView?.viewHeight {
//            if current.contentOffset.y + headerHeight > 0 {
//                placeholderOffset = current.contentOffset.y
//            } else {
//                placeholderOffset = -headerHeight
//            }
//
//            for index in 0 ..< self.controllers.count {
//                if index == page { continue }
//                self.controllers[index].scrollView()?.contentOffset = CGPoint(x: 0, y: placeholderOffset)
//            }
//
//        }
        
    }
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        let page = ceilf(Float(scrollView.contentOffset.x / UIScreen.main.bounds.width))
        self.headerView?.segments?.selectedIndex = Int(page)
    }
}
